import React, { useState } from 'react'
import { Layout, Row, Col, Upload, Modal, message, Divider, notification, Icon } from 'antd'
import { withRouter } from 'react-router-dom'

function UploadView({ getFieldDecorator, setPath, disabled }) {
    const [previewVisible, setPreviewVisible] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [previewImageName, setPreviewImageName] = useState('')
    const [fileList, setFileList] = useState()

    // 显示用于查看图片的 Modal 组件
    const showPreview = file => {
        setPreviewVisible(true)
        setPreviewImage(file.url || file.thumbUrl)
        setPreviewImageName(file.name)
    }

    // 隐藏用于查看图片的 Modal 组件
    const hidePreview = () => {
        setPreviewVisible(false)
    }

    const handleChange = ({ file, fileList }) => {
        console.log(file)
        setFileList(fileList.slice(-1))
        console.log(fileList)
        const { status, response } = file
        if (file.status === 'done') {
            let res = response
            if (res.code !== 0) {
                return notification.error({
                    message: `${file.name} 文件校验失败，失败原因：${res.message}.`
                })
            }
            setPath(res.result.urlPath)
        } else if (file.status === 'error') {
            notification.error({
                message: `${file.name} 文件上传失败.`
            })
        }
    }
    return (
        <Upload
            disabled={disabled ? disabled : false}
            fileList={fileList}
            name='icon'
            listType='picture-card'
            action='api/v1/icons'
            accept='image/png, image/jpeg, image/jpg'
            onChange={handleChange}
            onPreview={showPreview}>
            {previewImage ? (
                <img src={previewImage} alt='avatar' style={{ width: '100%' }} />
            ) : (
                <>
                    <Icon type='plus' />
                    <div style={{ marginTop: 8, color: '#666' }}>上传图片</div>
                </>
            )}
            <Modal visible={previewVisible} footer={null} onCancel={hidePreview}>
                <img src={previewImage} alt={previewImageName} style={{ width: '100%' }} />
            </Modal>
        </Upload>
    )
}

export default UploadView
